import React, { Component, Fragment } from "react";
import "antd/dist/antd.css"; // or 'antd/dist/antd.less'
import { Input, Button, List, Typography } from "antd";
import store from "./store"; //引入store文件夹下的index.js文件

import { getInputChangeAction,getAddItemAction,getDeleteItemAction } from "./store/actionCreators";

class TodoList extends Component {
  constructor(props) {
    super(props);
    this.state = store.getState();
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleStoreChange = this.handleStoreChange.bind(this);
    this.handleBtnClick = this.handleBtnClick.bind(this);
    store.subscribe(this.handleStoreChange); //通过store的subscribe方法来监听store中的数据变化，只要变化就执行this.handleStoreChange函数
  }

  render() {
    return (
      <div>
        <div style={{ marginTop: "10px", marginLeft: "10px" }}>
          <Input
            placeholder="Basic usage"
            style={{ width: "300px", marginRight: "10px" }}
            value={this.state.inputValue}
            onChange={this.handleInputChange}
          />
          <Button type="primary" onClick={this.handleBtnClick}>
            提交
          </Button>
          <List
            header={<div>Header</div>}
            footer={<div>Footer</div>}
            bordered
            dataSource={this.state.list}
            renderItem={(item, index) => (
              <List.Item onClick={this.handleItemDelete.bind(this, index)}>
                <Typography.Text mark>[ITEM]</Typography.Text> {item}
              </List.Item>
            )}
            style={{ width: "300px", marginTop: "10px" }}
          />
        </div>
      </div>
    );
  }

  //通过派发一个action给store，告诉store输入框发生了什么变化
  handleInputChange(e) {
    //action就是一个对象
    const action = getInputChangeAction(e.target.value)
    store.dispatch(action);
  }

  handleStoreChange() {
    this.setState(store.getState()); //将store中改变的数据用来更新当前组件的state
  }
  //点击“提交”按钮，通过dispatch向store派送一个action
  handleBtnClick() {
    const action = getAddItemAction();
    /* 创建了这句话（action）之后，如何将这句话传给store？
store提供了一个方法dispatch，将这句话（action）传给store */
    store.dispatch(action);
  }

  //列表项删除事件
  handleItemDelete(index) {
    const action = getDeleteItemAction(index);
    store.dispatch(action);
  }
}

export default TodoList;
